<template>
  <DynamicTable
    row-key="id"
    header-title="岗位管理"
    :data-request="Api.systemPost.postList"
    :columns="columns"
    bordered
    size="small"
  >
    <template #toolbar>
      <a-button
        type="primary"
        :disabled="!$auth('system:post:create')"
        @click="openMenuModal({})"
      >
        新增
      </a-button>
    </template>
  </DynamicTable>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import {
  baseColumns,
  searchFormSchema,
  type TableListItem,
  type TableColumnItem,
} from './columns';
import { baseSchemas } from './formSchemas';
import { useTable } from '@/components/core/dynamic-table';
import { useFormModal } from '@/hooks/useModal/';
import Api from '@/api/';

defineOptions({
  name: 'SystemPost',
});

const [DynamicTable, dynamicTableInstance] = useTable({
  formProps: {
    schemas: searchFormSchema,
  },
});

const [showModal] = useFormModal();

/**
 * @description 打开新增/编辑弹窗
 */
const openMenuModal = async (record: Partial<TableListItem>) => {
  const [formRef] = await showModal({
    modalProps: {
      title: `${record.id ? '编辑' : '新增'}岗位`,
      width: '50%',
      onFinish: async values => {
        console.log('新增/编辑岗位', values);
        if (record.id) {
          await Api.systemPost.postUpdate({ id: record.id }, values);
        } else {
          await Api.systemPost.postCreate(values);
        }

        dynamicTableInstance?.reload();
      },
    },
    formProps: {
      labelWidth: 120,
      schemas: baseSchemas,
    },
  });
  formRef?.setFieldsValue({
    ...record,
  });
};
const delRowConfirm = async (record: TableListItem) => {
  await Api.systemPost.postDelete({ id: record.id });
  dynamicTableInstance?.reload();
};

const columns: TableColumnItem[] = [
  ...baseColumns,
  {
    title: '操作',
    width: 250,
    dataIndex: 'ACTION',
    hideInSearch: true,
    fixed: 'right',
    actions: ({ record }) => [
      {
        label: '编辑',
        auth: {
          perm: 'system:post:update',
          effect: 'disable',
        },
        ifShow: (() => {
          return record.name !== '系统管理员';
        })(),
        onClick: () => openMenuModal(record),
      },
      {
        label: '删除',
        auth: 'system:post:delete',
        ifShow: (() => {
          return record.name !== '系统管理员';
        })(),
        popConfirm: {
          title: '你确定要删除吗？',
          placement: 'left',
          onConfirm: () => delRowConfirm(record),
        },
      },
    ],
  },
];
</script>
